//
//  NewsViewController.m
//  AVGirlShow
//
//  Created by 张良 on 2017/10/15.
//  Copyright © 2017年 张良. All rights reserved.
//

#import "NewsViewController.h"
#import <AFNetworking.h>
#import "NewsModel.h"
#import "NewsTableViewCell.h"
#import <MJExtension.h>
#import "DetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MJRefresh.h"

@interface NewsViewController () <UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *newsModels;
@property(nonatomic,assign) NSInteger page;
@end

@implementation NewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"NewsShow";
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
//    self.tableView.rowHeight = UITableViewAutomaticDimension;
//    self.tableView.estimatedRowHeight = 100;
    
    self.newsModels = [NSMutableArray array];
    self.tableView.rowHeight = 100;
    self.page = 1;
    
//    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ID"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([NewsTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"ID"];
    
    
    //  Ready to get work data , and set refresh control
    [self getWorkingDataWithClearType:YES];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.mj_header = header;
    
    
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//
//        [self.tableView.mj_header beginRefreshing];
//        [self getWorkingDataWithOperationType:YES];
//    }];

    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.refreshingTitleHidden = YES;
    footer.triggerAutomaticallyRefreshPercent = 0.5;
    self.tableView.mj_footer = footer;
//    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//
//        [self.tableView.mj_footer beginRefreshing];
//        [self getWorkingDataWithClearType:NO];
//    }];
    
    
    NSLog(@"tableView:%f",self.tableView.bounds.size.height);
    
    
    
//    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
//    [refreshControl addTarget:self action:@selector(refreshClick:) forControlEvents:UIControlEventValueChanged];
//    [self.tableView addSubview:refreshControl];
//    [refreshControl beginRefreshing];
//    [self refreshClick:refreshControl];
    
}

-(void) loadNewData{
    [self getWorkingDataWithClearType:YES];
    [self.tableView.mj_header endRefreshing];
}

-(void) loadMoreData{
    [self getWorkingDataWithClearType:NO];
    [self.tableView.mj_footer endRefreshing];
}



-(void) getWorkingDataWithClearType:(BOOL) clearData{
    
    NSString *url = [@"http://api.tianapi.com/" stringByAppendingFormat:@"%@%@",self.newsType,@"/"];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"key"] = @"6ae530ce4fc6f38cea94c597883c4c23";
    parameters[@"num"] = @"10";
    parameters[@"page"] = [NSString stringWithFormat:@"%ld",(long)self.page];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //        NSDictionary *attributes = [responseObject[@"result"][@"data"]];
        [NewsModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{
                     @"image" : @"picUrl",
                     @"date":@"ctime"
                     };
        }];
        if(clearData == YES){
            
            self.newsModels = [NewsModel mj_objectArrayWithKeyValuesArray:responseObject[@"newslist"]];
        }else{
            [self.newsModels addObjectsFromArray:[NewsModel mj_objectArrayWithKeyValuesArray:responseObject[@"newslist"]]];
        }
        
        [self.tableView reloadData];
        self.page++;
        
//                NSLog(@"%@",responseObject);
        //        NSLog(@"%@",self.girlModels);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
    
}


//- (void)refreshClick:(UIRefreshControl *)refreshControl {
//
//    NSString *url = @"http://api.tianapi.com/meinv/";
//
//    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
//    parameters[@"key"] = @"6ae530ce4fc6f38cea94c597883c4c23";
//    parameters[@"num"] = @"10";
//    parameters[@"page"] = [NSString stringWithFormat:@"%ld",(long)self.page];
//
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    [manager GET:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//        //        NSDictionary *attributes = [responseObject[@"result"][@"data"]];
//        [GirlModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
//            return @{
//                     @"image" : @"picUrl",
//                     @"date":@"ctime"
//                     };
//        }];
//        self.girlModels = [GirlModel mj_objectArrayWithKeyValuesArray:responseObject[@"newslist"]];
//
//        [refreshControl endRefreshing];
//        [self.tableView reloadData];
//        self.page++;
//
////        NSLog(@"%@",responseObject);
////        NSLog(@"%@",responseObject[@"newslist"]);
////                NSLog(@"%@",self.girlModels);
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//        NSLog(@"%@",error);
//    }];
//
////    [self.tableView reloadData];// 刷新tableView即可
//}

//-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//    NSLog(@"%f,%f",scrollView.contentOffset.y,scrollView.frame.size.height);
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DetailViewController *detailViewController = [[DetailViewController alloc] init];
    
    NewsModel *newsModel = self.newsModels[indexPath.row];
    
    detailViewController.view.backgroundColor = [UIColor whiteColor];
    detailViewController.url = newsModel.url;
    detailViewController.title = newsModel.title;
    detailViewController.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:detailViewController animated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
//    NSLog(@"%lu",self.girlModels.count);
    return self.newsModels.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID" ];
    
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ID"];
//    cell.imageView.image = [UIImage imageNamed:@"Logo"];
    NewsModel *newsModel = self.newsModels[indexPath.row];
//    [cell.girlImageView sd_setImageWithURL:[NSURL URLWithString:girl.image]];
//    cell.dj.image = [UIImage imageNamed:@"Logo"];
//    cell.imageView.image = [UIImage imageNamed:@"Logo"];
    [cell.newsImageView sd_setImageWithURL:[NSURL URLWithString:newsModel.image]];
    cell.titleLabel.text = newsModel.title;
    cell.detailLabel.text = newsModel.date;
    
//    CGSize itemSize = CGSizeMake(40, 40);
//    UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
//    CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
//    [cell.girlImageView.image drawInRect:imageRect];
//    cell.girlImageView.image = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
    
    
//    CGSize itemSize = CGSizeMake(80, 60);
//    UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
//    CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
//    [cell.girlImageView.image drawInRect:imageRect];
//    cell.girlImageView.image = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
    
//    NSLog(@"%@",girl);
//    tableViewCell.textLabel.text = girl.title;
//    [tableViewCell.imageView sd_setImageWithURL:[NSURL URLWithString:girl.image]];
    
    return cell;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
